<script lang="ts" setup>
import { useClientStore } from '@/stores/client'
import { inject, ref } from 'vue';
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

interface Tag {
  name: string
  color: string
}

interface PlayerInfo {
  puuid: string
  privacy?: string
}

interface MatchData {
  gameId: string
  participants?: any[]
}

const tags = ref<Tag[]>([])
const preTeam = inject<(data: { puuid: string; games: string[] }) => void>('preTeam')

function getTags(playerInfo: PlayerInfo, historyMatch: MatchData[]) {
  tags.value = []

  // 身份标签
  if (playerInfo?.puuid === useClientStore().userInfo.puuid) {
    tags.value.push({ name: t(`UserInfo.self`), color: 'blue' })
  } else if (playerInfo?.privacy === 'PRIVATE') {
    tags.value.push({ name: t(`UserInfo.privacy.private`), color: 'red' })
  }

  // 战绩分析
  const matchTags = analyzeMatchHistory(historyMatch, playerInfo)
  if (matchTags.length) {
    tags.value.push(...matchTags)
  }
}

function analyzeMatchHistory(matches: MatchData[], playerInfo: PlayerInfo): Tag[] {
  const tags: Tag[] = []
  const gameIdList: string[] = []

  if (!matches?.length) return tags

  let streakCount = 0
  let streakType: 'win' | 'lose' | 'finally' | null = null

  for (const match of matches) {
    const stats = match.participants?.[0]?.stats
    if (!stats) continue

    gameIdList.push(match.gameId)

    // 连胜/连败分析
    if (streakType !== 'finally') {
      if (streakType === null) {
        streakType = stats.win ? 'win' : 'lose'
        streakCount = 1
      } else if ((streakType === 'win' && stats.win) || (streakType === 'lose' && !stats.win)) {
        streakCount++
      } else {
        streakCount >= 3 && addStreakTag(tags, streakType, streakCount)
        streakType = 'finally'
      }
    }
  }

  if (preTeam && playerInfo?.puuid) {
    preTeam({ puuid: playerInfo.puuid, games: gameIdList })
  }

  return tags
}

function addStreakTag(tags: Tag[], type: 'win' | 'lose', count: number) {
  const tagType = type === 'win' ? 'winningStreak' : 'losingStreak'
  tags.push({
    name: t(`UserInfo.tags.${tagType}`, { count }),
    color: type === 'win' ? 'arcoblue' : 'red',
  })
}

defineExpose({ getTags })
</script>

<template>
  <a-tag v-for="(tag, index) in tags" :key="index" :color="tag.color" size="small">
    {{ tag.name }}
  </a-tag>
</template>
